package com.simba.server.task;

import java.util.LinkedList;
import java.util.List;

import com.simba.server.components.CommandExecutor;
import org.apache.log4j.Logger;


import com.simba.common.log.Log4jLogger;
import com.simba.common.log.LogTask;
import com.simba.common.log.LogUtil;
import com.simba.common.log.LoggerExecutor;

import com.simba.server.commands.impl.fetch.FetchSlotInfoCmd;
import com.simba.server.components.SlotManager;
import com.simba.server.components.data.SlotInfo;

public class SlotStatusTask extends Thread
{
	private final static Logger logger = Logger.getLogger(SlotStatusTask.class);
	private static final int REQUEST_INTERVAL = 10000;

	public SlotStatusTask()
	{
		this.setName("Slot-Status-Task");
	}

	@Override
	public void run()
	{
		while (!Thread.currentThread().isInterrupted())
		{
			try
			{
				this.reloadSlotConfig();
				this.reloadTshSlots();
				Thread.sleep(SlotStatusTask.REQUEST_INTERVAL);
			}
			catch (Exception ex)
			{
				if (ex instanceof InterruptedException)
				{
					Thread.currentThread().interrupt();
				}
				LogUtil.LogError(SlotStatusTask.logger,
						"Catch an exception [" + ex.getMessage() + "]");
			}
		}
	}

	private void reloadSlotConfig()
	{
		try
		{
			List<SlotInfo> slots = new LinkedList<>();
			boolean ret = CommandExecutor.executorSqlCommand(FetchSlotInfoCmd.NAME, slots,false);
			if (ret)
			{
				for (SlotInfo slotTmp : slots)
				{
					String slotId = slotTmp.getSlotId();

					SlotInfo slotInfo = SlotManager.getInstance().getSlotInfo(slotId);
					if (slotInfo == null)
					{
						continue;
					}

					slotInfo.setSlotDistrict(slotTmp.getSlotDistrict());
					slotInfo.setSlotWhetherUpload(slotTmp.getSlotWhetherUpload());

					slotInfo.setMasterPrinterId(slotTmp.getMasterPrinterId());
					slotInfo.setMasterPrinterIp(slotTmp.getMasterPrinterIp());

					slotInfo.setSlavePrinterId(slotTmp.getSlavePrinterId());
					slotInfo.setSlavePrinterIp(slotTmp.getSlavePrinterIp());
				}
			}
		}
		catch (Exception ex)
		{
			LoggerExecutor.getInstance()
					.execute(new LogTask(new Log4jLogger(SlotStatusTask.logger),
							"[SlotStatusTask.reloadSlotConfig] reload slots config error: " + ex,
							LogTask.ERROR));
		}
	}

	private void reloadTshSlots()
	{
		try
		{
			SlotManager.getInstance().reloadTshSlots();
		}
		catch (Exception ex)
		{
			LogUtil.LogError(SlotStatusTask.logger, "Catch an exception [" + ex.getMessage() + "]");
		}
	}
}
